package com.tencent.wxcloudrun.config;

import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户信息拦截器
 */
@Component
public class UserInfoInterceptor implements HandlerInterceptor {

    private static final String USER_INFO_HEADER = "X-WX-OPENID"; // 假设用户信息存储在X-WX-OPENID头中

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String userInfo = request.getHeader(USER_INFO_HEADER);
        if (StrUtil.isBlank(userInfo)) {
            throw new CustomException("非正常微信小程序请求！");
        }
        UserContext.setUserInfo(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.clear();
    }
}